package com.lm.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.lm.common.core.constant.CommonConstants;
import com.lm.common.core.constant.SecurityConstants;
import com.lm.common.core.util.R;
import com.lm.common.security.userdetail.ScmUser;
import com.lm.upms.api.dto.UserInfo;
import com.lm.upms.api.entity.SysUser;
import com.lm.upms.api.feign.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户详细信息
 *
 * @author
 * @date
 */
@Service
public class ScmUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteUserService remoteUserService;

//    // cacheManager注入有异常，需要解决
//    @Autowired
//    private CacheManager cacheManager;

//    @Resource
//    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        Cache cache = cacheManager.getCache("user_details");
//        if (cache != null && cache.get(username) != null) {
//            return (ScmUser) cache.get(username).get();
//        }

//        Object codeObj = redisTemplate.opsForValue().get("user_details");
//        if (codeObj != null) {
//            return (ScmUser) codeObj;
//        }

        R<UserInfo> result = remoteUserService.findByUsername(username);
        UserDetails userDetails = getUserDetails(result);

        // cache.put(username, userDetails);
        // redisTemplate.opsForValue().set("user_details", userDetails);

        return userDetails;
    }

    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(R<UserInfo> result) {
        if (result == null || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserInfo userInfo = result.getData();
        Set<String> authSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(userInfo.getRoles())) {
            // 获取角色
            Arrays.stream(userInfo.getRoles()).forEach(role -> authSet.add(SecurityConstants.ROLE + role));
            // 获取资源
            authSet.addAll(Arrays.asList(userInfo.getPermissions()));

        }
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(authSet.toArray(new String[0]));
        SysUser user = userInfo.getSysUser();

        // 构造security用户
        return new ScmUser(user.getUserId(), user.getDeptId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(),
                StrUtil.equals(user.getStatus(), CommonConstants.STATUS_NORMAL), true, true, true, authorities);
    }

}
